<template>
  <div>
    <div style="margin: 10px 70px 10px 0;text-align: end;">
      <el-button type="primary" @click="addForm()">添加编辑框</el-button>
    </div>
    <el-form :inline="true" v-for="(item, index) in state.formInline"  :key="index" label-width="120px" class="demo-form-inline">
      <el-form-item label="课程名称:" required>
        <el-input v-model="item.name_zh" placeholder="请输入课程名称"></el-input>
      </el-form-item>
      <el-form-item label="课程英文名称:" required>
        <el-input v-model="item.name" placeholder="请输入课程英文名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="deleteForm(index)">删除</el-button>
      </el-form-item>
    </el-form>
    <div>
      <el-button @click="submitForm(1)">取消</el-button>
      <el-button type="primary" @click="submitForm(2)">提交</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref,reactive,computed,onMounted} from 'vue';
import { ElMessage ,} from 'element-plus';
import API from "@/utils/api";
import { defineProps, defineEmits } from 'vue';
const emits = defineEmits(['closeAddLesson']);
const props = defineProps({
  parmas: Object,
});
const state = reactive({
  formInline:[{name_zh:'',name:''}],
})
// 新增行
const addForm = (() => {
  state.formInline.push({name_zh:'',name:''})
})
// 删除行
const deleteForm = ((index) => {
  state.formInline.splice(index, 1)
})
// 提交数据
const submitForm = ((type) => {
  if(type === 1) {
    return emits('closeAddLesson',type)
  }
  let stateMessage = false
  state.formInline.forEach((item,index) => {
    if(!item.name_zh || !item.name) { stateMessage = true }
  })
  if(stateMessage) {
    return ElMessage.warning('请确认课程名称或课程英文名称是否填写') 
  }
  API.lessonList.addLesson({degrees_id:props.parmas.degrees_id,courses:state.formInline},(res) =>{
    if(res.code == 0) {
      emits('closeAddLesson',type)
      ElMessage.success('提交成功')
    }
  })
})
onMounted(() => {
  if(props.parmas.list.length > 0) {
    props.parmas.list.forEach((item) => {
      delete item.degrees_id
      delete item.id
    })
    const listData_ = props.parmas.list.filter(item => item !== "" && item !== null && item !== undefined);
    state.formInline = JSON.parse(JSON.stringify(listData_))
  }
})
</script>

<style lang="scss" scoped>

</style>